package com.example.myapplication;

import android.util.Log;

import androidx.annotation.NonNull;

import io.reactivex.Observable;
import io.reactivex.ObservableEmitter;
import io.reactivex.ObservableOnSubscribe;
import io.reactivex.Observer;
import io.reactivex.Scheduler;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Function;
import io.reactivex.schedulers.Schedulers;

public class Tooldemo {
    // 步骤1：创建被观察者 Observable & 发送事件
    // 在主线程创建被观察者 Observable 对象
    // 所以生产事件的线程是：主线程
    Observable <Integer> observable = Observable.create(new ObservableOnSubscribe<Integer>() {
        @Override
        public void subscribe(@NonNull ObservableEmitter<Integer> emitter) throws Exception {
            emitter.onNext(1);
            emitter.onNext(2);
            emitter.onComplete();
            Log.d("TAG", " 被观察者 Observable的工作线程是: " + Thread.currentThread().getName());
        }
    });

    // 步骤2：创建观察者 Observer 并 定义响应事件行为
    // 在主线程创建观察者 Observer 对象
    // 所以接收 & 响应事件的线程是：主线程
    public void test1(){
        Observer<Integer> observer = new Observer<Integer>() {
            @Override
            public void onSubscribe(@NonNull Disposable d) {
                try {
                    Thread.sleep(10000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                Log.d("TAG", "开始采用subscribe连接");
                Log.d("TAG", " 观察者 Observer的工作线程是: " + Thread.currentThread().getName());
                // 打印验证
            }

            @Override
            public void onNext(@NonNull Integer integer) {
                Log.d("TAG", "对Next事件"+ integer +"作出响应"  );
            }

            @Override
            public void onError(@NonNull Throwable e) {
                Log.d("TAG", "对Error事件作出响应");
            }

            @Override
            public void onComplete() {
                Log.d("TAG", "对Complete事件作出响应");
            }
        };

        observable
                .subscribeOn(Schedulers.newThread())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(observer);
    }
}
